package cn.ltgodm.template.web.controller.user;

import cn.ltgodm.template.common.annotation.Log;
import cn.ltgodm.template.common.annotation.Validation;
import cn.ltgodm.template.common.domain.AjaxResult;
import cn.ltgodm.template.common.domain.entity.LoginUser;
import cn.ltgodm.template.common.domain.vo.RoleVO;
import cn.ltgodm.template.common.enums.BusinessType;
import cn.ltgodm.template.common.utils.SecurityUtils;
import cn.ltgodm.template.common.utils.StringUtils;
import cn.ltgodm.template.user.domain.param.RoleParam;
import cn.ltgodm.template.user.domain.param.RoleQueryParam;
import cn.ltgodm.template.user.service.RoleService;
import cn.ltgodm.template.user.service.UserService;
import cn.ltgodm.template.user.service.impl.PermissionService;
import cn.ltgodm.template.user.service.impl.TokenService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author ltgodm
 * @date 2024-03-26 19:16:22
 * 角色信息
 */
@RestController
@RequestMapping("/user/role")
@Tag(name = "角色管理")
@ApiSupport(author = "ltgodm")
public class RoleController {

    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    @GetMapping("/list")
    @Operation(summary = "分页查询角色列表")
    @PreAuthorize("hasAuthority('system:role:query')")
    public IPage<RoleVO> list(@ParameterObject RoleQueryParam roleQueryParam) {
        return roleService.selectRoleList(roleQueryParam);
    }


    @GetMapping("/{roleId}")
    @Operation(summary = "根据角色ID获取角色信息")
    @PreAuthorize("hasAuthority('system:role:query')")
    public AjaxResult getInfo(@PathVariable Long roleId) {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    @PostMapping
    @Operation(summary = "新增角色")
    @PreAuthorize("hasAuthority('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated(Validation.AddGroup.class) @RequestBody RoleParam queryParam) {
        if (!roleService.checkRoleNameUnique(queryParam)) {
            throw new RuntimeException("新增角色'" + queryParam.getRoleName() + "'失败，角色名称已存在");
        }
        if (!roleService.checkRoleKeyUnique(queryParam)) {
            throw new RuntimeException("新增角色'" + queryParam.getRoleName() + "'失败，角色权限已存在");
        }
        int row = roleService.insertRole(queryParam);
        if (row >= 1) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @PutMapping
    @Operation(summary = "修改角色")
    @PreAuthorize("hasAuthority('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated(Validation.EditGroup.class) @RequestBody RoleParam queryParam) {
        if (!roleService.checkRoleNameUnique(queryParam)) {
            throw new RuntimeException("修改角色'" + queryParam.getRoleName() + "'失败，角色名称已存在");
        }
        if (!roleService.checkRoleKeyUnique(queryParam)) {
            throw new RuntimeException("修改角色'" + queryParam.getRoleName() + "'失败，角色权限已存在");
        }
        int row = roleService.updateRole(queryParam);
        if (row >= 0) {
            // 更新缓存用户权限
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @PutMapping("/changeStatus")
    @Operation(summary = "修改角色状态")
    @PreAuthorize("hasAuthority('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    public AjaxResult changeStatus(@Validated RoleParam queryParam) {
        int row = roleService.updateRoleStatus(queryParam);
        if (row >= 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @DeleteMapping("/{roleIds}")
    @Operation(summary = "删除角色")
    @PreAuthorize("hasAuthority('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable Long[] roleIds) {
        int row = roleService.deleteRoleByIds(roleIds);
        if (row >= 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }




}
